from flask import Blueprint, request, jsonify, current_app, url_for, send_from_directory
from app import csrf
from app.constants import UEDITOR_UPLOAD_PATH
from app.utils.util import upload_image
import os
import re
import json

upload_controller = Blueprint("upload", __name__)

@upload_controller.route("/upload", methods=["GET", "POST"])
@csrf.exempt
def do_upload():
    action = request.args.get('action')
    result = {}
    if action == 'config':
        config_path = os.path.join(current_app.static_folder, 'admin', 'ueditor','config.json')
        with open(config_path,'r',encoding='utf-8') as fp:
            result = json.loads(re.sub(r'\/\*.*\*\/','',fp.read()))
    elif action == 'uploadimage':
        result = upload_image(request)

    return jsonify(result)

@upload_controller.route('/upload/<dirname>/<filename>')
def files(dirname, filename):
    return send_from_directory(UEDITOR_UPLOAD_PATH, dirname + '/' + filename)